package com.ohuang.action

import android.Manifest
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.File
import java.io.FileOutputStream

class SendActivity : AppCompatActivity() {
    val TAG = "SendActivity"
    var isRun = false
    var uri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_send)
        Log.d(TAG, "onCreate: " + intent)
        val intent = intent
        val action = intent.action
        val type = intent.type

        if (Intent.ACTION_SEND == action && type != null) {
            uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)


        }
        var tv_name = findViewById<TextView>(R.id.tv_name)
        tv_name.text = "uri:" + uri
        requestPower()
        findViewById<Button>(R.id.btn_copyToFile).setOnClickListener {
            fileName=findViewById<EditText>(R.id.edit_name).text.toString()
            Thread {
                Log.d(TAG, "onCreate: isRun=$isRun")
                if (isRun || uri == null) {
                    return@Thread
                }
                isRun = true
                try {
runOnUiThread { showDialog() }
                    var uriFileName = getUriFileName(uri!!)
                    var filePath =
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/" + "com.ohuang.action" + "/" + uriFileName
                    Log.d(TAG, "onCreate: " + filePath)
                    copyToFile(uri!!, filePath)
                    tv_name.post {
                        Toast.makeText(
                            this@SendActivity,
                            "成功复制到/Download/com.ohuang.action/${uriFileName}",
                            Toast.LENGTH_LONG
                        ).show()
                        findViewById<TextView>(R.id.tv_tip).text =
                            "已复制到/Download/com.ohuang.action/${uriFileName}"
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "copyFile " + e)
                }
                runOnUiThread { dialog?.dismiss() }
                isRun = false
            }.start()
        }
    }
    private var dialog: Dialog? = null

    private fun showDialog() {
        if (dialog == null) {
            dialog = ProgressDialog(this)
        }
        dialog?.setCanceledOnTouchOutside(false)
        (dialog as ProgressDialog)?.setMessage("正在加载中")
        dialog?.show()
    }

    private var fileName=""
    private fun getUriFileName(uri: Uri): String {
        if (!TextUtils.isEmpty(fileName)){
            return fileName
        }
        var toString = uri.toString()
        Log.d(TAG, "getUriFileName: " + toString)
        var split = toString.split("/")
        return split[split.size - 1]
    }

    //申请读写权限
    fun requestPower() {
//判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            ) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    1
                )
            }
        }
    }

    private fun copyToFile(uri: Uri, filePath: String) {

        var openInputStream = contentResolver.openInputStream(uri)
        if (openInputStream == null) {
            Log.e(TAG, "copyToFile:获取不到InputStream uri=$uri")
        }
        var file = File(filePath)
        if (!file.parentFile!!.exists()) {
            file.parentFile?.mkdirs()
        }

        var fileOutputStream = FileOutputStream(file)
        fileOutputStream.use { fos ->

            openInputStream?.use { ips ->
                val buffer = ByteArray(1024)

                var len = 0
                while (ips.read(buffer).also { len = it } != -1) {
                    fos.write(buffer, 0, len)
                }
            }

        }

    }
}